package we.caro;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import we.common.CCommonHandler;
import we.core.bean.CDataContainer;
import we.core.bean.CRoom;
import we.core.bean.CUser;
import we.database.CDataController;
import we.database.IDataController;
import we.dispatcher.CDispatcherHandler;
import we.extension.CExtensionUtility;
import we.extension.CSystemEvent;
import we.extension.IExtension;
import we.socialcontroller.CSocialUserInfo;
import we.socialcontroller.ISocialController;
import we.socialcontroller.CSocialController;


public class CaroExtension  implements IExtension {


    

    public class CounterTimer implements Runnable {
        private CUser user;
  
        public CounterTimer(CUser user) {
            super();
            this.user = user;
        }
  
        @Override
        public void run() {
            user.properties.put("active", String.valueOf(false));
        }
    }
    
    private final String CMD = "_cmd";
    public final static String PREFIX_CARO = "caro_";
    public static final String SUFFIX_INFO = "_info";

    private ScheduledExecutorService exectutor;

    private HashMap<Integer, CaroGame> gameMap; // map roomID -> game Caro
    private ISocialController zmController;


    @Override
    public void init() {
        exectutor = Executors.newScheduledThreadPool(10);
        gameMap = new HashMap<Integer, CaroGame>();
        zmController = CSocialController.GetController();
    }

    private int caculateEXPPoint(int X, int Y) {
        float absHieu = Math.abs(X - Y);
        int max = Math.max(0, 16 - Math.round(absHieu / 16));
        return Math.min(32, max);
    }


    private void createRoomFriend(CUser owner, CUser guest) {
        try {
            int roomNewId =
                CExtensionUtility.instance().createRoom(owner, "", 2, "");

            if (roomNewId == -1) {
            } else {
                // cho 2 doi thu vao phong
                CCommonHandler.trace("room ID join: " + roomNewId);
                CExtensionUtility.instance().joinRoom(owner, owner.roomId,
                                                     roomNewId, "");
                CExtensionUtility.instance().joinRoom(guest, guest.roomId,
                                                     roomNewId, "");
                owner.properties.put("isBusy", "true");
                guest.properties.put("isBusy", "true");
                
                owner.properties.put("betLv", "" + 50);
                owner.properties.put("betLv", "" + 50);
                
                
                CaroGame game = new CaroGame(owner.userId, guest.userId);
                game.newGame(owner.userId);
                gameMap.put(owner.roomId, game);

                JSONObject myParams = new JSONObject();
                myParams.put("betLv", 50);

                JSONArray users = new JSONArray();
                JSONObject user1 = new JSONObject();
                user1.put("username", owner.username);
                user1.put("userId", owner.userId);
                users.put(user1);
                user1 = new JSONObject();
                user1.put("username", guest.username);
                user1.put("userId", guest.userId);
                users.put(user1);

                myParams.put("users", users);
                JSONObject response =
                    new JSONObject().put(CMD, "JR").put("params", myParams);
                CRoom room = CDataContainer.instance().getRoom(roomNewId);
                List<CUser> playerList = room.getPlayerList();
                for (CUser user : playerList) {
                    CDispatcherHandler.instance().sendResponse(user.channel,
                                                             response);
                }
            }
        } catch (Exception e) {
            CCommonHandler.writeErrLog(e);
        }
    }

    public void instancePlay(JSONObject params, CUser u) {
        boolean active;
        int betLv;

        try {
            active = params.getBoolean("active");
            u.properties.put("active", String.valueOf(active));
            if (active) {
                // neu tim doi thu choi ngay
                betLv = params.getInt("betLv");
                int gold = Integer.parseInt(u.properties.get("gold"));

                JSONObject json = new JSONObject().put("_cmd", "IP");
                if (gold < betLv) {
                    json.put("param", new JSONObject().put("errorCode", 1));
                    CDispatcherHandler.instance().sendResponse(u.channel, json);
                    return;
                }
                // thoa man dieu kien gold > betLv
                u.properties.put("betLv", String.valueOf(betLv));
                //tim kiem doi thu

                // sau 5s trang thai active cua u thanh false
                CounterTimer counterTimer = new CounterTimer(u);
                exectutor.schedule(counterTimer, 5, TimeUnit.SECONDS);

                CUser competitor = CaroUtility.instance().findCompetitor(u);
                if (competitor != null) {
                    //tim thay doi thu
                    CUser owner = u;
                    CUser guest = competitor;
                    int roomNewId =
                        CExtensionUtility.instance().createRoom(owner, "", 2,
                                                               "");
                    if (roomNewId == -1) {
                        json.put("param",
                                 new JSONObject().put("errorCode", -1));
                        CDispatcherHandler.instance().sendResponse(u.channel,
                                                                 json);
                    } else {
                        // cho 2 doi thu vao phong
                        CCommonHandler.trace("room ID join: " + roomNewId);
                        CExtensionUtility.instance().joinRoom(owner,
                                                             owner.roomId,
                                                             roomNewId, "");
                        CExtensionUtility.instance().joinRoom(guest,
                                                             guest.roomId,
                                                             roomNewId, "");
                        owner.properties.put("active", "false");
                        guest.properties.put("active", "false");
                        CaroGame game =
                            new CaroGame(owner.userId, guest.userId);
                        game.newGame(owner.userId);
                        gameMap.put(owner.roomId, game);

                        JSONObject myParams = new JSONObject();
                        myParams.put("betLv", betLv);

                        JSONArray users = new JSONArray();
                        JSONObject user1 = new JSONObject();
                        user1.put("username", owner.username);
                        user1.put("userId", owner.userId);
                        users.put(user1);
                        user1 = new JSONObject();
                        user1.put("username", guest.username);
                        user1.put("userId", guest.userId);
                        users.put(user1);

                        myParams.put("users", users);
                        JSONObject response =
                            new JSONObject().put(CMD, "JR").put("params",
                                                                myParams);
                        CRoom room =
                            CDataContainer.instance().getRoom(roomNewId);
                        List<CUser> playerList = room.getPlayerList();
                        for (CUser user : playerList) {
                            CDispatcherHandler.instance().sendResponse(user.channel,
                                                                     response);
                        }
                    }

                }

                else {
                    json.put("param", new JSONObject().put("errorCode", 2));
                    CDispatcherHandler.instance().sendResponse(u.channel, json);
                }
            }

        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }

    public void gameReady(CUser user) {
        CaroGame game = gameMap.get(user.roomId);
        CCommonHandler.trace(" user Ready  : " + user.username);
        CRoom room = CDataContainer.instance().getRoom(user.roomId);
        List<CUser> playerList = room.getPlayerList();
        if (game != null) {
            try {
                JSONObject response = new JSONObject().put("CMD", "GR");
                JSONObject params =
                    new JSONObject().put("errorCoe", 0).put("username",
                                                            user.username);
                response.put("params", params);
                for (CUser u : playerList) {
                    CDispatcherHandler.instance().sendResponse(u.channel,
                                                             response);
                }
            } catch (JSONException e) {
                CCommonHandler.writeErrLog(e);
            }

            game.ready(user.userId);
            if (game.isStarted()) {
                //game bat dau thi thong bao cho nguoi trong phong
                JSONObject json;
                try {
                    json =
new JSONObject().put(CMD, "GS").put("params", new JSONObject().put("whoTurn",
                                                                   game.getFirstMove()));
                    for (CUser u : playerList) {
                        CDispatcherHandler.instance().sendResponse(u.channel,
                                                                 json);
                    }
                    //Map.Entry it =
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                JSONObject response = new JSONObject().put("CMD", "GR");
                JSONObject params =
                    new JSONObject().put("errorCoe", -1).put("username",
                                                             user.username);
                response.put("params", params);
                for (CUser u : playerList) {
                    CDispatcherHandler.instance().sendResponse(u.channel,
                                                             response);
                }
            } catch (JSONException e) {
                CCommonHandler.writeErrLog(e);
            }

        }

    }

    private CUser[] find2Player(int roomId) {
        CRoom room = CDataContainer.instance().getRoom(roomId);
        List<CUser> userList = room.getPlayerList();
        CUser[] result = new CUser[2];
        CaroGame game = gameMap.get(roomId);
        if (game != null) {
            int playerOne = game.getPlayerOne();
            int playerTwo = game.getPlayerTwo();
            for (CUser user : userList) {
                if (user.userId == playerOne)
                    result[0] = user;
                else if (user.userId == playerTwo)
                    result[1] = user;
            }
        }
        return result;
    }

    private void solveWinLose(CUser winner, CUser loser) {
        CaroGame game = gameMap.get(winner.roomId);

        try {
            Map<String, Object> winnerInfo =
                (Map)CDataController.GetController().get(PREFIX_CARO +
                                                        winner.username +
                                                        SUFFIX_INFO);
            winnerInfo.get("gold");
            int goldOne = (Integer)winnerInfo.get("gold");
            int expOne = (Integer)winnerInfo.get("exp");
            int numWinOne = (Integer)winnerInfo.get("numWin");
            // int numLoseOne = (Integer)winnerInfo.get("numLose");

            Map<String, Object> loserInfo =
                (Map)CDataController.GetController().get(PREFIX_CARO +
                                                        winner.username +
                                                        SUFFIX_INFO);

            int goldTwo = (Integer)loserInfo.get("gold");
            int expTwo = (Integer)loserInfo.get("exp");
            //int numWinTwo = (Integer)loserInfo.get("numWin");
            int numLoseTwo = (Integer)loserInfo.get("numLose");

            int betLv = Integer.parseInt(winner.properties.get("betLv"));

            int p = caculateEXPPoint(expOne, expTwo);

            winner.properties.put("gold", String.valueOf(goldOne + betLv));
            winner.properties.put("exp", String.valueOf(expOne + p));
            winner.properties.put("numWin", String.valueOf(numWinOne + 1));

            winnerInfo.put("gold", goldOne + betLv);
            winnerInfo.put("exp", expOne + p);
            winnerInfo.put("numWin", numWinOne + 1);

            loser.properties.put("gold", String.valueOf(goldTwo - betLv));
            loser.properties.put("exp", String.valueOf(expTwo - p));
            loser.properties.put("numLose", String.valueOf(numLoseTwo + 1));

            loserInfo.put("gold", goldOne - betLv);
            loserInfo.put("exp", expOne - p);
            loserInfo.put("numLose", numLoseTwo + 1);

            CDataController.GetController().set(PREFIX_CARO + winner.username +
                                               SUFFIX_INFO, winnerInfo);
            CDataController.GetController().set(PREFIX_CARO + loser.username +
                                               SUFFIX_INFO, loserInfo);


            try {
                JSONObject response = new JSONObject().put(CMD, "GSTOP");
                JSONObject params = new JSONObject();
                params.put("winner", winner.userId).put("loser", loser.userId);
                boolean canContinue = (goldTwo - betLv) >= betLv;
                if (!canContinue)
                    game.setStopped(true);
                else
                    game.setStopped(false);
                params.put("canContinue", canContinue);
                response.put("params", params);
                List<CUser> listUser =
                    CDataContainer.instance().getRoom(winner.roomId).getPlayerList();
                for (CUser user : listUser) {
                    CDispatcherHandler.instance().sendResponse(user.channel,
                                                             response);
                }

            } catch (JSONException e) {
                CCommonHandler.writeErrLog(e);
            }
        } catch (Exception e) {
            CCommonHandler.writeErrLog(e);
        }


    }


    private void chessMove(JSONObject jsonObject, CUser u) {
        int cell;
        try {
            cell = jsonObject.getInt("cell");
            CaroGame game = gameMap.get(u.roomId);
            if (game != null) {
                CaroGame.RESULT result = game.move(u.userId, cell);
                if (result != CaroGame.RESULT.ERROR) {
                    JSONObject response = new JSONObject().put(CMD, "CM");
                    JSONObject params =
                        new JSONObject().put("cell", cell).put("whoTurn",
                                                               u.userId);
                    response.put("params", params);
                    List<CUser> listUser =
                        CDataContainer.instance().getRoom(u.roomId).getPlayerList();
                    for (CUser user : listUser) {
                        CDispatcherHandler.instance().sendResponse(user.channel,
                                                                 response);
                    }
                }


                if (result == CaroGame.RESULT.DRAW) {
                    JSONObject response = new JSONObject().put(CMD, "GSTOP");
                    JSONObject params = new JSONObject();

                    params.put("winner", JSONObject.NULL).put("loser",
                                                              JSONObject.NULL);
                    boolean canContinue = true;
                    params.put("canContinue", canContinue);
                    List<CUser> listUser =
                        CDataContainer.instance().getRoom(u.roomId).getPlayerList();
                    for (CUser user : listUser) {
                        CDispatcherHandler.instance().sendResponse(user.channel,
                                                                 response);
                    }
                    game.newGame(game.getFirstMove());

                } else if (result == CaroGame.RESULT.PLAYER_ONE_WIN ||
                           result == CaroGame.RESULT.PLAYER_TWO_WIN) {
                    CUser[] userArr = find2Player(u.roomId);
                    int goldOld;
                    try {
                        //Map<Integer, Object> infoOne =  (Map)DataController.GetController().get(LoginHandler.PREFIX_CARO + userOne.username + LoginHandler.SUFFIX_INFO );
                        //Map<Integer, Object> infoTwo =  (Map)DataController.GetController().get(LoginHandler.PREFIX_CARO + userTwo.username + LoginHandler.SUFFIX_INFO );

                        if (result == CaroGame.RESULT.PLAYER_ONE_WIN) {
                            solveWinLose(userArr[0], userArr[1]);
                            game.newGame(userArr[0].userId);
                        } else if (result == CaroGame.RESULT.PLAYER_TWO_WIN) {
                            solveWinLose(userArr[1], userArr[0]);
                            game.newGame(userArr[1].userId);
                        }

                    } catch (Exception e) {
                        CCommonHandler.writeErrLog(e);
                    }

                }
            } else
                CCommonHandler.trace(" game = null ");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void chatRoom(JSONObject params, CUser u) {

        try {
            String message = params.getString("message");

            JSONObject json = new JSONObject();
            json.put(CMD, "chat");
            json.put("params",
                     new JSONObject().put("sender", u.username).put("message",
                                                                    message));
            // TEST tu gui cho minh
            // DispatcherHandle.instance().sendResponse(u.channel, json);
            if (CDataContainer.instance().getRoom(u.roomId) != null) {
                //tim nhung nguoi trong danh sach
                List<CUser> playerList =
                    CDataContainer.instance().getRoom(u.roomId).getPlayerList();
                for (CUser user : playerList) {
                    CDispatcherHandler.instance().sendResponse(user.channel,
                                                             json);
                }
            }
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }

    
    private void outRoom(CUser u, boolean isDisconnected) {
        CaroGame game = gameMap.get(u.roomId);

        try {
            JSONObject respone = new JSONObject().put(CMD, "OR");
            JSONObject params = new JSONObject().put("username", u.username);
            respone.put("params", params);
            if (u.roomId == -1)
                return;
            List<CUser> playerList =
                CDataContainer.instance().getRoom(u.roomId).getPlayerList();
            for (CUser user : playerList) {
                CDispatcherHandler.instance().sendResponse(user.channel,
                                                         respone);
            }
            // chua xu ly broadcast cho ban be
            // game da dung thi ko phai xu ly gi
            if (!game.isStopped()) {
                // game chua bat dau thi ko xu ly gi
                if (game.isStarted()) {
                    CUser[] userArr = find2Player(u.roomId);
                    if (u.userId == userArr[0].userId) {
                        solveWinLose(userArr[1], userArr[0]);
                    } else if (u.userId == userArr[1].userId) {
                        solveWinLose(userArr[0], userArr[1]);
                    }
                }
            }
            if (!isDisconnected)
              CExtensionUtility.instance().outRoom(u, u.roomId);
            game.setStopped(true);
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }


    private void getUserInfo(CUser u) {
        JSONArray jsonFriends = getFriendList(u, false);
        JSONObject jsonResponse = new JSONObject();

        try {
            jsonResponse.put(CMD, "GUI");
            JSONObject jsonParams = new JSONObject();

            long userId =
                zmController.getLoggedInUser(u.properties.get("seesionKey"));
            CSocialUserInfo infoMe = zmController.getUserInfo(userId);

            JSONObject jsonMe = new JSONObject().put("userId", userId);
            jsonMe.put("username", infoMe.getUsername());
            jsonMe.put("avatar", infoMe.getHeadurl());

            UserCaroInfo userCaroInfo =
                UserCaroInfo.getUserCaroInfo(u.username);
            jsonMe.put("numWin", userCaroInfo.getNumWin());
            jsonMe.put("numLose", userCaroInfo.getNumLose());
            jsonMe.put("gold", userCaroInfo.getGold());
            jsonMe.put("exp", userCaroInfo.getExp());

            jsonResponse.put("errorCode", 0);
            jsonParams.put("me", jsonMe);
            jsonParams.put("friends", jsonFriends);

            jsonResponse.put("params", jsonParams);
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        } catch (Exception e) {
            CCommonHandler.writeErrLog(e);

            try {
                jsonResponse.put(CMD, "GUI").put("errorCode", -1);

            } catch (JSONException f) {
                CCommonHandler.writeErrLog(f);
            }
        }

        CDispatcherHandler.instance().sendResponse(u.channel, jsonResponse);

    }

    private JSONArray getFriendList(CUser u, boolean send) {

        try {
            JSONObject response = new JSONObject().put(CMD, "GRL");
            JSONObject params = new JSONObject();
            JSONArray jsonArr = new JSONArray();
            String sessionKey = u.properties.get("seesionKey");
            List<Long> listId = zmController.getFriendList(sessionKey);
            List<CSocialUserInfo> listFriend = zmController.getUserInfo(listId);

            for (CSocialUserInfo userInfo : listFriend) {
                CUser user =
                    CDataContainer.instance().getUser(userInfo.getUsername());
                UserCaroInfo userCaroInfo =
                    UserCaroInfo.getUserCaroInfo(userInfo.getUsername());
                JSONObject jsonFriend = new JSONObject();
                jsonFriend.put("username",
                               userInfo.getUsername()).put("avatar",
                                                           userInfo.getHeadurl());
                if (userCaroInfo != null) {
                    jsonFriend.put("numWin", userCaroInfo.getNumWin());
                    jsonFriend.put("numLose", userCaroInfo.getNumLose());
                    jsonFriend.put("gold", userCaroInfo.getGold());
                    jsonFriend.put("exp", userCaroInfo.getExp());
                    jsonFriend.put("alias", userInfo.getDisplayname());
                    boolean isOnline = (user != null);
                    jsonFriend.put("isOnline", isOnline);
                    if (isOnline) {
                        boolean isBusy =
                            Boolean.parseBoolean(user.properties.get("isBusy"));
                        jsonFriend.put("isBusy", isBusy);
                    }
                    jsonArr.put(jsonFriend);
                }
            }
            params.put("friends", jsonArr);
            response.put("params", params);
            if (send)
                CDispatcherHandler.instance().sendResponse(u.channel, response);
            return jsonArr;
        } catch (Exception e) {
            CCommonHandler.writeErrLog(e);
        }
        return null;
    }

    public void changeStatus(SocketChannel channel, String userName,
                             Map<String, Object> properties) {
        JSONObject json = new JSONObject();
        try {
            json.put(CMD, "changeStatus");
            JSONObject jsonParams = new JSONObject().put("username", userName);
            JSONArray jsonArr = new JSONArray();
            Iterator<Map.Entry<String, Object>> it =
                properties.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> next = it.next();
                jsonArr.put(new JSONObject().put("name",
                                                 next.getKey()).put("value",
                                                                    next.getValue()));
            }
            jsonParams.put("properties", jsonArr);
            json.put("params", jsonArr);
            CDispatcherHandler.instance().sendResponse(channel, json);
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }


    private void invitePlay(JSONObject params, CUser u) {
        try {
            String nameInvitee = params.getString("receiver");
            CUser invitee = CDataContainer.instance().getUser(nameInvitee);
            if (invitee == null) {
                JSONObject json =
                    new JSONObject().put(CMD, "invite").put("errorCode", 1);
                CDispatcherHandler.instance().sendResponse(u.channel, json);                
                return;
            }
            // gui thang toi receiver chua kiem tra j
            u.properties.put("invitee", invitee.username);
            
            boolean isAutoDeny = false;
            if (invitee.properties.containsKey("isAutoDeny"))
                isAutoDeny = Boolean.parseBoolean( invitee.properties.get("isAutoDeny") );
            if (isAutoDeny){
                refuse(u.username, invitee);
                return;
            }
            JSONObject json =
                new JSONObject().put(CMD, "invite").put("params", new JSONObject().put("sender",
                                                                                       u.username));
            CDispatcherHandler.instance().sendResponse(invitee.channel, json);

            new JSONObject().put(CMD, "invite").put("errorCode", 1);
            CDispatcherHandler.instance().sendResponse(u.channel,
                                                     new JSONObject().put(CMD,
                                                                          "invite").put("errorCode",
                                                                                        0));
            
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }

    private void acceptInvite(JSONObject params, CUser u) {

        try {
            String inviterName = params.getString("inviter");
            CUser inviter = CDataContainer.instance().getUser(inviterName);
            String inviteeName = inviter.properties.get("invitee");
            if (inviteeName != null && inviteeName.equals(u.username)){
                JSONObject jsonResponse = new JSONObject().put(CMD, "accept");            
                jsonResponse.put("errorCode", 0);
                CDispatcherHandler.instance().sendResponse(inviter.channel,
                                                         jsonResponse);            
                createRoomFriend(inviter, u);
            } 
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }

    private void cancelInvitation(CUser u) {
        u.properties.remove("invitee");
    }
    
    private void refuse(String inviterName, CUser u) {
        CUser inviter = CDataContainer.instance().getUser(inviterName);
        try{
          if (inviter.properties.get("invitee").equals(u.username) ){              
              try {
                  JSONObject jsonResponse = new JSONObject().put(CMD, "refuse");
                  jsonResponse.put("params", new JSONObject().put("username", u.username) );
                  CDispatcherHandler.instance().sendResponse(inviter.channel, jsonResponse);
              } catch (JSONException e) {
                  CCommonHandler.writeErrLog(e);
              }
            }
        } catch (NullPointerException e){
          CCommonHandler.writeErrLog(e);
        }
    }
    
    private void autoDenyInvitatition(JSONObject params, CUser u) {    
        try {
             boolean active = params.getBoolean("active");
              u.properties.put("isAutoDeny",String.valueOf(active));
        } catch (JSONException e) {
            CCommonHandler.writeErrLog(e);
        }
    }

    @Override
    public void handleClientRequest(JSONObject data, CUser u) {
        // test chat boardcast all
        CCommonHandler.trace("client request");
        CCommonHandler.trace(" User name :" + u.username + "\n data :" +
                    data.toString());
        if (data.has(CMD)) {
            try {
                String cmd = data.getString(CMD);
                if (cmd.equals("chat")) {
                    chatRoom(data.getJSONObject("params"), u);
                } else if (cmd.equals("IP")) {
                    // choi ngay - instance play
                    instancePlay(data.getJSONObject("params"), u);
                } else if (cmd.equals("GR")) {
                    // ready
                    gameReady(u);
                } else if (cmd.equals("CM")) {
                    chessMove(data.getJSONObject("params"), u);
                } else if (cmd.equals("OR")) {
                    outRoom(u, false);
                } else if (cmd.equals("GFL")) {
                    getFriendList(u, true);
                } else if (cmd.equals("GUI")) {
                    getUserInfo(u);
                } else if (cmd.equals("invite")) {
                    invitePlay(data.getJSONObject("params"), u);
                } else if (cmd.equals("accept")) {
                    acceptInvite(data.getJSONObject("params"), u);
                } else if (cmd.equals("cancelInvi")){
                    cancelInvitation(u);
                } else if (cmd.equals("refuse")){
                    refuse(data.getJSONObject("params").getString("inviter") , u);
                } else if (cmd.equals("ADI")){
                    autoDenyInvitatition(data.getJSONObject("params"), u);
                }


            } catch (JSONException e) {
                CCommonHandler.writeErrLog(e);
            }
        }
    }

    private IDataController membase = CDataController.GetController();
    private final String SUFFIX_FRIEND_LIST = "FriendList";

    private void loginSystemEvent(Map<String, Object> params) {
        List<CUser> friendList;
        try {
            String username = ((CUser)params.get("username")).username;
            // if (membase.getCache( "" ) == null)

        } catch (Exception ex) {
            CCommonHandler.writeErrLog(ex);
        }
    }

    @Override
    public void handleSystemEvent(CSystemEvent event) {
        CCommonHandler.trace(" Server event");
        if (event == null) {
            CCommonHandler.trace("event = null");
            return;
        }
        Map<String, Object> params = event.getParams();
        CCommonHandler.trace("params : " + params);
        List<SocketChannel> list;
        // test login ok

        if (params.get("eventName").equals(CSystemEvent.SystemEventType.LOGIN)) {
            CUser u = (CUser)params.get("user");
            CCommonHandler.trace("Login user in server: " +
                        CDataContainer.instance().getUsers().size());        
        } else if (params.get("eventName").equals(CSystemEvent.SystemEventType.DISCONNECT)) {
            CUser u = (CUser)params.get("user");
            System.out.println("Disconnect user: " + u.username +
                               "  . Number users in server: " +
                               CDataContainer.instance().getUsers().size());
            outRoom(u, true);
        } else if (params.get("eventName").equals(CSystemEvent.SystemEventType.CREATE_ROOM)) {
            CCommonHandler.trace("create room");
            CRoom room = (CRoom)params.get("room");
            CCommonHandler.trace(room.getRoomId());

        } else if (params.get("eventName").equals(CSystemEvent.SystemEventType.JOIN_ROOM)) {
            CCommonHandler.trace("join room");
        }
    }

    @Override
    public void destroy() {

    }
}
